package com.example.pagination;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

/* Pagination 分页标签 视图部分 
 * 
 **/
public class Pagination extends TagSupport {

	private static final long serialVersionUID = 219404950561578929L;

	/*
	 * Pagination 分页标签 辅助对象
	 * 
	 * @see AriesSoftStudio.Pagination.PagHelper
	 */
	private PagHelper pageHelper = null;

	private HttpSession session = null;
	private HttpServletRequest request = null;

	// 分页对象的变量名名称
	private String name = "ph";

	// 页大小
	private int pageSize = 10;

	// 分页请求所附加参数的名称
	private String paramName = "pageIndex";

	// 分页请求提交路径
	private String action = "";

	// 在页面显示的页数连接数量
	private int pageLinks = 5;

	// 是否允许排序
	private boolean allowSorting = false;

	// 是否降序排列
	private boolean isDESC = true;

	// 排序字段
	private String sequenceField = null;

	// 当查询不到任何信息时所显示的信息
	private String msg = "没有查询到任何记录!!";

	private String method = "get";

	public void setName(String name) {
		this.name = name;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public void setParamName(String paramName) {
		this.paramName = paramName;
	}

	public void setAction(String action) {
		this.action = action;
	}

	public void setPageLinks(int pageLinks) {
		this.pageLinks = pageLinks;
	}

	public void setAllowSorting(boolean allowSorting) {
		this.allowSorting = allowSorting;
	}

	public void setDESC(boolean isDESC) {
		this.isDESC = isDESC;
	}

	public void setSequenceField(String sequenceField) {
		this.sequenceField = sequenceField;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public void setMethod(String method) {
		if ("post".equalsIgnoreCase(method)) {
			this.method = method;
		}
		if ("get".equalsIgnoreCase(method)) {
			this.method = method;
		}
	}

	public Pagination() {
	}

	public int doEndTag() throws JspException {
		return EVAL_PAGE;// 继续执行网页，SKIP_PAGE为立刻停止执行网页
	}

	public int doStartTag() throws JspException {
		session = pageContext.getSession();
		request = (HttpServletRequest) pageContext.getRequest();
		JspWriter out = pageContext.getOut();
		try {
			initPagination();
			out.print(initNavigation());
		} catch (IOException e) {
			e.printStackTrace();
		}
		session.removeAttribute(name);// 移除PageHelper对象.
		return SKIP_BODY;// 忽略标签体，EVAL_BODY_INCLUDE为执行标签体
	}

	private void initPagination() {
		pageHelper = (PagHelper) session.getAttribute(name);
		pageHelper = (pageHelper == null) ? new PagHelper() : pageHelper;
		pageHelper.setPageSize(pageSize);
		pageHelper.setAllowSorting(allowSorting);
		pageHelper.setSequenceField(sequenceField);
		pageHelper.setIsDESC(isDESC);
	}

	private String initNavigation() {
		int start = 1, end = pageHelper.getPagesCount();
		StringBuilder sb = new StringBuilder();

		if (pageHelper.getRowsCount() > 0) {
			sb.append("<style type='text/css'>\n");
			sb.append("form a {font-size: 12px;text-decoration: none;}\n");
			sb
					.append("form div{line-height: 18px; height: 18px; width: 100%;}\n");
			sb.append("form .left {float: left;margin-left: 10px;}\n");
			sb
					.append("form .right {float: right;font-size: 12px;margin: 2px 10px auto;}\n");
			sb
					.append("form input {width: 20px;padding: 0px;font-size: 10px;}\n");
			sb.append("</style>\n");
			sb.append("<script type='text/javascript'>");
			sb.append("function {1}_go(i){\n");
			sb.append("var form = document.getElementById('{1}');\n");
			sb.append("form.elements['" + paramName + "'].value=i;\n");
			sb.append("form.submit();\n}</script>\n");

			sb.append("<form id='{1}' action='" + action + "' method='"
					+ method + "'>\n");
			sb.append("\t<div>\n\t\t<span class='left'>\n");
			sb.append("\t\t\t<a href='javascript:{1}_go(1);'>首页</a>\n");
			if (!pageHelper.getIsFirstPage()) {
				sb.append("\t\t\t<a href='javascript:{1}_go("
						+ (pageHelper.getPageIndex() - 1) + ");'>上一页</a>\n");
			}
			// 当当前页-1大于分页用户界面总显示页数的1/2时,显示的页数从PageIndex-总显示页数的1/2为数值开始显示
			if (pageHelper.getPageIndex() - 1 > pageLinks / 2) {
				start = pageHelper.getPageIndex() - pageLinks / 2;
			}
			// 当当前页+分页用户界面总显示页数的1/2大于总页数时,显示的页数以总页数为数值结束显示
			if (pageHelper.getPageIndex() + pageLinks / 2 < pageHelper
					.getPagesCount()) {
				end = start + pageLinks;
			}
			// 当结束页为总页数时,开始页为(总页数-显示页数)+1,结束页数为总页数+1.
			if (end == pageHelper.getPagesCount()) {
				start = (pageHelper.getPagesCount() - pageLinks) + 1;
				end += 1;
			}
			if (pageHelper.getPagesCount() <= pageLinks) {
				start = 1;
				end = pageHelper.getPagesCount() + 1;
			}
			for (; start < end; start++) {
				if (start == pageHelper.getPageIndex()) {
					sb
							.append("\t\t\t<a class='current' href='javascript:{1}_go("
									+ start + ");'>" + start + "</a>\n");
				} else {
					sb.append("\t\t\t<a href='javascript:{1}_go(" + start
							+ ");'>" + start + "</a>\n");
				}
			}
			if (!pageHelper.getIsLastPage()) {
				sb.append("\t\t\t<a href='javascript:{1}_go("
						+ (pageHelper.getPageIndex() + 1) + ");'>下一页</a>\n");
			}

			sb.append("\t\t\t<a href='javascript:{1}_go("
					+ pageHelper.getPagesCount() + ");'>尾页</a>\n");

			/* -----表单参数----- */
			sb.append("\t\t\t<input type='text' name='" + paramName
					+ "' value='1' style='height: 14px;'/>\n");
			Enumeration enums = request.getParameterNames();
			while (enums.hasMoreElements()) {
				String param = (String) enums.nextElement();
				String value = request.getParameter(param);
				if (!paramName.equals(param)) {
					sb.append("\t\t\t<input type='hidden' name='" + param
							+ "' value='" + value + "'/>\n");
				}
			}
			// ==============================

			sb
					.append("\t\t\t<input type='submit' value='GO' style='height: 17px;'/>\n");
			sb.append("\t\t</span>\n\t\t<span class='right'>");
			sb.append(String.format("当前第%1s页,共%2s页(%3s条记录)", pageHelper
					.getPageIndex(), pageHelper.getPagesCount(), pageHelper
					.getRowsCount()));
			sb.append("</span>\n\t</div>\n</form>\n");
		} else {
			sb.append("<label>" + msg + "</label>");
		}
		return sb.toString().replace("{1}", id);
	}
}